﻿using System;
using System.Web;
using LeastPrivilege.CustomBasicAuthentication.Management;

namespace LeastPrivilege.CustomBasicAuthentication
{
	public partial class UnregisteredAuthenticationModule : IHttpModule
	{
		// Event Registration
		public void Init(HttpApplication context)
		{
			context.AuthenticateRequest += OnEnter;
			context.EndRequest += OnLeave;
		}

		void OnEnter(object sender, EventArgs e)
		{
			HttpContext context = HttpContext.Current;

			// Check if module is enabled
			if (!Configuration.Enabled)
				return;

			// Check if SSL is required and enabled
			if (Configuration.RequireSSL && !context.Request.IsSecureConnection)
				throw new HttpException(403, "SSL required for Basic Authentication");

			// Check if basic authentication header is present
			// if yes - try to authenticate
			// if no  - check if anonymous access is allowed
			//		if yes - let authorization decide when authentication is needed
			//		if no  - try to authenticate
			// Try to athenticate user - otherwise set status code and end request
			if (IsHeaderPresent)
			{
				if (!AuthenticateUser())
				{
					DenyAccess();
				}
			}
			else
			{
				// If anonymous requests are not allowed - end the request
				if (!IsAnonymousAllowed)
				{
					DenyAccess();
				}
			}
		}

		void OnLeave(object sender, EventArgs e)
		{
			// Check if module is enabled
			if (Configuration.Enabled)
			{
				if (HttpContext.Current.Response.StatusCode == 401)
				{
					SendAuthenticationHeader();
				}
			}
		}

		public void Dispose() { }
	}
}
